package util;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;

/**
 * 文件操作工具类
 *
 * @author guohan
 *
 */
public class FileUtils {

	public static byte[] getFile2Byte(File file) {
		if (!file.exists() || file.length() == 0) {
			return null;
		}
		byte[] by = new byte[(int) file.length()];
		try (InputStream is = new FileInputStream(file);
				ByteArrayOutputStream bytestream = new ByteArrayOutputStream();) {
			byte[] bb = new byte[2048];
			int ch;
			while ((ch = is.read(bb)) != -1) {
				bytestream.write(bb, 0, ch);
			}
			by = bytestream.toByteArray();
		} catch (Exception ex) {
			throw new RuntimeException("转换出错", ex);
		}
		return by;
	}

	/**
	 * 文件排序 按修改时间正序排
	 *
	 * @param fileList
	 * @return
	 */
	public static List<File> sortFileAsc(List<File> fileList) {
		fileList.sort(new Comparator<File>() {
			@Override
			public int compare(File f1, File f2) {
				return (int) (f1.lastModified() - f2.lastModified());
			}
		});
		return fileList;
	}

	/**
	 * 根据正则清除不需要的文件
	 *
	 * @param files
	 * @param removeRegex
	 * @return
	 */
	public static List<File> clearByRegex(File[] files, String removeRegex) {
		List<File> fileList = new ArrayList<File>();
		if (files != null) {
			for (File file : files) {
				if (!file.getName().matches(removeRegex)) {
					fileList.add(file);
				}
			}
		}
		return fileList;
	}

	/**
	 * 删除文件夹下面所有的文件，然后删除文件夹
	 *
	 * @param folder
	 */
	public static void deleteFolder(File folder) {
		File[] fileArr = folder.listFiles();
		for (int i = 0; i < fileArr.length; i++) {
			fileArr[i].delete();
		}
		folder.delete();
	}

	/**
	 * 清除文件夹下面所有的文件,不删除文件夹
	 *
	 * @param dir
	 */
	public static void clearAllFiles(String dir) {
		if (dir != null && !"".equals(dir)) {
			File dirFile = new File(dir);
			if (dirFile.exists()) {
				File[] files = dirFile.listFiles();
				if (files != null) {
					for (int i = 0; i < files.length; i++) {
						files[i].delete();
					}
				}
			}
		}

	}

	/**
	 * 给定字节，写入文件
	 *
	 * @param outDir
	 * @param fileName
	 * @param bytes
	 * @throws IOException
	 */
	public static void writeToFile(String outDir, String fileName, byte[] bytes) {
		File dir = new File(outDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		try (FileOutputStream fos = new FileOutputStream(outDir + File.separator + fileName.trim());
				FileChannel fc = fos.getChannel();) {
			ByteBuffer bb = ByteBuffer.wrap(bytes);
			fc.write(bb);
			fc.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void writeToFile(String path, byte[] bytes) {
		try (FileOutputStream fos = new FileOutputStream(path); FileChannel fc = fos.getChannel();) {
			ByteBuffer bb = ByteBuffer.wrap(bytes);
			fc.write(bb);
			fc.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写入文件
	 *
	 * @param path
	 * @param content
	 */
	public static void writeFile(String path, String content) {
		try (BufferedWriter bw = new BufferedWriter(new FileWriter(path))) {
			bw.write(content);
			bw.flush();
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取文件的第一行
	 *
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static String readOneLine(String filePath) throws IOException {
		String line = "";
		File file = new File(filePath);
		if (!file.exists()) {
			return "";
		}
		InputStream in = new FileInputStream(filePath);
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		while ((line = reader.readLine()) != null) {
			break;
		}
		reader.close();
		return line;
	}
	
	
	public static String readAllWithTrim(String filePath) throws IOException {
		StringBuilder sb = new StringBuilder();
		String line = "";
		File file = new File(filePath);
		if (!file.exists()) {
			return "";
		}
		InputStream in = new FileInputStream(filePath);
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		while ((line = reader.readLine()) != null) {
			sb.append(line.trim());
		}
		reader.close();
		return sb.toString();
	}

	/**
	 * 将key v值写到文件
	 * @param path
	 * @param valueMap
	 */
	public static void writeWithKeyV(String path,Map<String,Object> valueMap){
		if(valueMap != null && !valueMap.isEmpty()){
			Set<String> keys = valueMap.keySet();
			StringBuffer sb = new StringBuffer();
			for(String key:keys){
				sb.append(key).append("=").append(valueMap.get(key)).append("\r\n");
			}
			if(sb.length() > 0){
				writeFile(path,sb.toString());
			}
		}
	}


}
